<?php
/*spxd*/
class weixin_templatemsg{


function loadWxTemplateMsg(){

    $tmp= app::get('whyshopseckill')->getConf('wx_template_source');

    if($tmp!=""){
        preg_match_all('/\{\{(\S+)\}\}/iU', $tmp, $result);
//print_r($result);exit;
        $json=array();
        foreach($result[1] as $k => $v){
            $v=explode('$',$v);
            $color="";

            if($v[0]){
                //格式
                $rs_name=explode('=',$v[0]);
                $rs_name[0]=str_replace('.DATA','',$rs_name[0]);//jianming

                if($v[1]){
                    //颜色设置
                    $rs_color=explode('=',$v[1]);
                    $color=$rs_color[1];//jianming

                }

                if($rs_name[0]) {
                    if(1==2 && ($rs_name[0] == 'first' || $rs_name[0] == 'remark')) {
$json[] = <<<EOT
"{$rs_name[0]}": {
"value":"{$rs_name[1]}",
"color":"{$color}"}
EOT;
                        }
                        else{
$json[] = <<<EOT
"{$rs_name[0]}": {
"value":"%s",
"color":"{$color}"}
EOT;
                        }
                    }

            }
            }
            return $json;
        }


    }
  /*发送模板消息*/

  function sendTempateMessage($open_id,$postData){

      $postData=$postData[0];
      $paramsData['method']='message/template/send';
      $paramsData['ToUserName']=$open_id;
      $libweixin=kernel::single('weixin_wechat');

      $bind_id_rs=app::get('weixin')->model('bind')->getList('*',array('status'=>'active'));
      $bind_id=$bind_id_rs[0]['id'];
      file_put_contents(DATA_DIR.'/testseckill.txt',date('Y-m-d H:i:s')."\r\n"."bind_id:".var_export($bind_id,true),FILE_APPEND);

      /**/
      if(!$access_token = $libweixin->get_basic_accesstoken($bind_id)){

          $msg = "token 错误，请稍后重试";
          file_put_contents(DATA_DIR.'/testseckill.txt',date('Y-m-d H:i:s')."\r\n"."msg:".var_export($msg,true),FILE_APPEND);
          return false;
      }

      $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";

      file_put_contents(DATA_DIR.'/testseckill.txt',date('Y-m-d H:i:s')."\r\n"."token_url:".var_export($url,true),FILE_APPEND);

      // 由于微信不直接认json_encode处理过的带中文数据的信息，这里做个转换
      //$postData = preg_replace ( "/\\\u([0-9a-f]{4})/ie", "iconv('UCS-2BE', 'UTF-8', pack('H*', '$1'));", $postData );
      $httpclient = kernel::single('base_httpclient');
      //print_r($postData);exit;
      $response = $httpclient->set_timeout(6)->post($url, $postData);
      //
      file_put_contents(DATA_DIR.'/testseckill.txt',date('Y-m-d H:i:s')."\r\n"."response:".var_export($response,true),FILE_APPEND);

      $result = json_decode($response, true);
      if( $result['errcode']==0 ){
          logger::info('秒杀提醒发送成功:'.print_r($result,1));
         // return true;
      }else{
          $msg = "秒杀提醒发送成功,微信返回的错误码为 {$result['errcode']}";
          logger::info($msg);
        //  return false;
      }
      return $result;
      /**/
  }


    /*
    {{first.DATA}}
产品名称：{{keyword1.DATA}}
购买数量：{{keyword2.DATA}}
订单金额：{{keyword3.DATA}}
下单时间：{{keyword4.DATA}}
快递方式：{{keyword5.DATA}}
{{remark.DATA}}
  {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",            
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "keynote1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keynote2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keynote3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }
    */
    function getTempateMessage($action,$member_id,$order_id){
      $objOrder=$this->system->loadModel('trading/order');
      $order=$objOrder->getFieldById($order_id);


      $orderitems=$objOrder->getItemList($order_id);//商品


$goodsurl=MAIN_HOST.'/waptouch/?product-'.$orderitems[0]['goods_id'].'.html';//$this->system->mkUrl('product','index',array($orderitems[0]['goods_id']));//商品链接



$fromUsernameRs=$objOrder->db->selectRow('select weixin_opend_id,weixin_nickname from sdb_members where member_id='.$member_id);
$fromUsername=$fromUsernameRs['weixin_opend_id'];


      switch ($action) {
      case 'order/create':
        # code...
      $order_detail_url=$this->system->mkUrl('member','orderdetail',array($order_id));
       $textTpl=' {
           "touser":"%s",
           "template_id":"oISxBeAK6G5W9-Q180FgneZtGpH9_qfto46e337aVTQ",
           "url":"'.$order_detail_url.'",            
           "data":{
                   "keyword1": {
                       "value":"%s",
                       "color":"#173177"
                   },
                   "keyword2":{
                       "value":"%s",
                       "color":"#173177"
                   },
                   "keyword3": {
                       "value":"%s元",
                       "color":"#173177"
                   },
                   "keyword4": {
                       "value":"%s",
                       "color":"#173177"
                   },
                    "keyword5": {
                       "value":"%s",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"%s",
                       "color":"#173177"
                   }
           }
       }';  


       $resultStr=array(sprintf($textTpl, $fromUsername, $order['tostr'], $order['itemnum'],$order['total_amount'], date('Y-m-d H:i:s',$order['createtime']),$order['shipping'],'请及时支付'));






        break;
      
        case 'order/payed':
        # code...

/*{{first.DATA}}
订单商品：{{keyword1.DATA}}
订单编号：{{keyword2.DATA}}
支付金额：{{keyword3.DATA}}
支付时间：{{keyword4.DATA}}
{{remark.DATA}}*/

        # code...
      $order_detail_url=$goodsurl;//MAIN_HOST.'/waptouch/?member-'.$order_id.'-orderdetail.html';
       $textTpl=' {
           "touser":"%s",
           "template_id":"Yk4Wgj-u6lWTbTdVtAi1jQcJuTR-Vd_wlbEfdqu7VUY",
           "url":"'.$order_detail_url.'",            
           "data":{
                   "first": {
                       "value":"%s",
                       "color":"#173177"
                   },

                   "keyword1": {
                       "value":"%s",
                       "color":"#173177"
                   },
                   "keyword2":{
                       "value":"%s",
                       "color":"#173177"
                   },
                   "keyword3": {
                       "value":"%s元",
                       "color":"#173177"
                   },
                   "keyword4": {
                       "value":"%s",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"%s",
                       "color":"#173177"
                   }
           }
       }';  

        $resultStr=array(sprintf($textTpl, $fromUsername, '您的订单已支付成功',$order['tostr'],$order['order_id'],$order['total_amount'], date('Y-m-d H:i:s'),'感谢您对百年乾合股份的支持，我们会在24至48小时内发货；如有疑问，请您直接通过微信公众号和我们联系。'));


        break;


        case 'order/ticheng':
        # code...

/*


{{first.DATA}}
购买客户：{{keyword1.DATA}}
订单总金额：{{keyword2.DATA}}
{{remark.DATA}}

感谢您的推荐！您将在30天内收取推荐佣金！
购买客户：Chris
订单总金额：1246元
推荐留学生境外接机服务，获取丰厚佣金！

$arrcomorder = $this->db->selectrow( "select * from sdb_rcomp2p_orders where s_member_id=".intval( $smid )." and r_member_id=".intval( $rmid )." and order_id=".$this->db->quote( $order_id ) );
if ( $arrcomorder && $arrcomorder['rstatus'] == '0' )
{
    $sqlInsert = "update sdb_rcomp2p_orders set rstatus='1' where s_member_id=".intval( $smid )." and r_member_id=".intval( $rmid )." and order_id=".$this->db->quote( $order_id );
    $this->db->exec( $sqlInsert );
    $objadvance = $this->system->loadModel( "member/advance" );
    if ( 0 < $arrcomorder['com_amount1'] )
    {
            $objadvance->add( $smid, $arrcomorder['com_amount1'], "", $msg, "", $order_id, "", "一级下线订单提成".$order_id );
    }
    if ( $arrcomorder['s_pp_member_id'] && 0 < $arrcomorder['com_amount2'] )
    {
            $objadvance->add( $arrcomorder['s_pp_member_id'], $arrcomorder['com_amount2'], "", $msg, "", $order_id, "", "二级下线订单提成".$order_id );
    }
}
*/

        # code...


$arrcomorder = $this->db->selectrow( "select * from sdb_rcomp2p_orders where order_id='".$order_id."'");
file_put_contents(HOME_DIR.'/ticheng.txt', var_export("select * from sdb_rcomp2p_orders order_id='".$order_id."'",true));
  if($arrcomorder){

      $order_detail_url=$goodsurl;//MAIN_HOST.'/waptouch/?member-rcorderstat.html';

      if(0 < $arrcomorder['com_amount1']){

$r1=$this->db->selectRow('select weixin_opend_id,weixin_nickname from sdb_members where member_id='.$arrcomorder['s_member_id']);


      if($r1['weixin_opend_id']){
       $textTpl=' {
           "touser":"%s",
           "template_id":"WmyWNjG-CPfs_1Rhnmqc7hDS6Ok1EOCBEAWJNQyttZk",
           "url":"'.$order_detail_url.'",            
           "data":{

                          "first": {
                       "value":"%s",
                       "color":"#173177"
                   },

                   "keyword1": {
                       "value":"%s",
                       "color":"#173177"
                   },
                   "keyword2":{
                       "value":"%s",
                       "color":"#173177"
                   },
    
                   "remark":{
                       "value":"%s",
                       "color":"#173177"
                   }
           }
       }';  

       $resultStr[0] = sprintf($textTpl, $r1['weixin_opend_id'],'尊敬的VIP客户，您名下的粉丝，所下的订单已支付成功；管理员审核后，您的推荐奖励即可到账，您的粉丝越多，将来您的收益越高。继续努力哦！点击可查看此订单物品详情！', $fromUsernameRs['weixin_nickname'],$order['total_amount'],'奖励金额：'.$arrcomorder['com_amount1']);
        }
     }
      if($arrcomorder['s_pp_member_id'] && 0 < $arrcomorder['com_amount2']){

$r2=$this->db->selectRow('select weixin_opend_id,weixin_nickname from sdb_members where member_id='.$arrcomorder['s_pp_member_id']);

        if($r2['weixin_opend_id']){

       $textTpl=' {
           "touser":"%s",
           "template_id":"WmyWNjG-CPfs_1Rhnmqc7hDS6Ok1EOCBEAWJNQyttZk",
           "url":"'.$order_detail_url.'",            
           "data":{

                          "first": {
                       "value":"%s",
                       "color":"#173177"
                   },

                   "keyword1": {
                       "value":"%s",
                       "color":"#173177"
                   },
                   "keyword2":{
                       "value":"%s",
                       "color":"#173177"
                   },
    
                   "remark":{
                       "value":"%s",
                       "color":"#173177"
                   }
           }
       }';  

       $resultStr[1] = sprintf($textTpl, $r2['weixin_opend_id'],'尊敬的VIP客户，您名下的粉丝，所下的订单已支付成功；管理员审核后，您的推荐奖励即可到账，您的粉丝越多，将来您的收益越高。继续努力哦！', $fromUsernameRs['weixin_nickname'],$order['total_amount'],'奖励金额：'.$arrcomorder['com_amount2']);

     }
     }
}

        break;




        default:
        # code...
        break;


    }
      return $resultStr;
  }


}
?>